from django.db import models
from django.contrib.auth.models import User
from space.game import controllers
from space.game.controllers import technologies
from random import seed, random
from math import floor
seed()


class Planet(models.Model):

    MIN_SIZE            = 100
    MAX_SIZE            = 200

    user                = models.OneToOneField(User)
    name                = models.CharField(max_length=100, null=False)
    galaxy              = models.IntegerField(default=1, null=False)
    solar_system        = models.IntegerField(default=1, null=False)
    position            = models.IntegerField(default=1, null=False)
    size                = models.IntegerField(default=150, null=False)

    colonisation_date   = models.DateTimeField(auto_now_add=True)
    last_update         = models.DateTimeField(auto_now_add=True)

    def get_controller(self):
        return controllers.Planet(self)


class Building(models.Model):
    name                = models.CharField(max_length=100, null=False)

    def get_controller(self):
        controllers_list = dir(controllers.buildings)
        for controller_name in controllers_list:
            controller  = getattr(controllers.buildings, controller_name)
            if controller.name == self.name:
                return controller(self)
        return None

class Construction(models.Model):
    bulding             = models.OneToOneField(Building)
    planet              = models.OneToOneField(Planet)
    level               = models.IntegerField(default=1, null=False)

    def get_controller(self):
        return self.bulding.get_controller()

    def up(self):
        self.level += 1

class Technology(models.Model):
    name                = models.CharField(max_length=100, null=False)

    def get_controller(self):
        controllers_list = dir(technologies)
        for controller_name in controllers_list:
            if controller_name[0] == '_':
                continue
            controller  = getattr(technologies, controller_name)
            print controller.name.lower(), self.name.lower()
            if controller.name.lower() == self.name.lower():
                return controller(self)
        return None

class Research(models.Model):
    user                = models.OneToOneField(User)
    technology          = models.OneToOneField(Technology)
    level               = models.IntegerField(default=1, null=False)

    def get_controller(self):
        return self.technology.get_controller()

    def up(self):
        self.level += 1


